package com.wsc.wisdomchinaqinghe.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.AbPermissionUtils;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.MessageActivity;
import com.wsc.wisdomchinaqinghe.activitity.PersonInfoActivity;
import com.wsc.wisdomchinaqinghe.activitity.SettingActivity;
import com.wsc.wisdomchinaqinghe.activitity.ShouLiCenterActivity;
import com.wsc.wisdomchinaqinghe.activitity.minemodule.MyBackActivity;
import com.wsc.wisdomchinaqinghe.activitity.minemodule.MyBaoMingActivity;
import com.wsc.wisdomchinaqinghe.activitity.minemodule.MyFaBuActivity;
import com.wsc.wisdomchinaqinghe.activitity.minemodule.MyYuYueActivity;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.MyModuleInfo;
import com.wsc.wisdomchinaqinghe.javaBean.MyModuleStateBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.javaBean.StreetInfoListBean;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.myatotextview.AutofitTextView;

import java.io.File;
import java.lang.ref.SoftReference;

import de.hdodenhof.circleimageview.CircleImageView;

public class MineFragment extends Fragment implements View.OnClickListener,ContributorView{
    private ImageView setting;
    private ImageView iv_message,baoming_point,fabu_point,shenqing_point,yuyue_point,fankui_point,iv_edit;
    private CircleImageView head_icon;
    private TextView nicker_name;
    private RelativeLayout bottom_content_one,bottom_content_two,bottom_content_three,
    bottom_content_four,bottom_content_five;
    private boolean ishide = false;
    private ContributorPresenter contributorPresenter;
    private Context context;
    private String userid;
    private final String MY_MODULE_STATE_FLAG="MY_MODULE_STATE_FLAG";
    private String myMoudleInfoString;
    private final String MY_MODULE_INFO_FLAG="MY_MODULE_INFO_FLAG";
    private Bitmap initBitmap;
    private AutofitTextView tv_score;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_mine,container,false);
        context=getActivity();
        contributorPresenter = new ContributorPresenter(this, context);
        initview(view);
        return view;
    }

    private void initview(View view) {
        tv_score=(AutofitTextView) view.findViewById(R.id.tv_score);
        head_icon= (CircleImageView) view.findViewById(R.id.head_icon);
        setting= (ImageView) view.findViewById(R.id.setting);
        iv_message= (ImageView) view.findViewById(R.id.message);
        nicker_name= (TextView) view.findViewById(R.id.nicker_name);
        iv_edit=(ImageView) view.findViewById(R.id.iv_edit);
        bottom_content_one= (RelativeLayout) view.findViewById(R.id.bottom_content_one);
        bottom_content_two= (RelativeLayout) view.findViewById(R.id.bottom_content_two);
        bottom_content_three= (RelativeLayout) view.findViewById(R.id.bottom_content_three);
        bottom_content_four= (RelativeLayout) view.findViewById(R.id.bottom_content_four);
        bottom_content_five= (RelativeLayout) view.findViewById(R.id.bottom_content_five);
        baoming_point= (ImageView) view.findViewById(R.id.baoming_point);
        fabu_point= (ImageView) view.findViewById(R.id.fabu_point);
        shenqing_point= (ImageView) view.findViewById(R.id.shenqing_point);
        yuyue_point= (ImageView) view.findViewById(R.id.yuyue_point);
        fankui_point= (ImageView) view.findViewById(R.id.fankui_point);

        head_icon.setOnClickListener(this);
        iv_edit.setOnClickListener(this);
        setting.setOnClickListener(this);
        iv_message.setOnClickListener(this);
        bottom_content_one.setOnClickListener(this);
        bottom_content_two.setOnClickListener(this);
        bottom_content_three.setOnClickListener(this);
        bottom_content_four.setOnClickListener(this);
        bottom_content_five.setOnClickListener(this);

    }

    private void getData()
    {
        userid= Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        myMoudleInfoString=Tools.getSharedPreferencesStrings(Constant.SharePreferenceMyModuleInfo,"",context);
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", context);
        String cidNumber="";
        if (locationString.length() > 0) {
            StreetInfoListBean streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber=streetInfoListBean.getId();
        }
        contributorPresenter.getMyModuleState(userid,cidNumber,MY_MODULE_STATE_FLAG);
        contributorPresenter.getMyModuleInfo(userid,MY_MODULE_INFO_FLAG);
    }

    @Override
    public void onLoadContributorStart(String flag) {
        if(flag.equals(MY_MODULE_INFO_FLAG))
        {
            try {
                MyModuleInfo myModuleInfo=JsonTools.jsonStringToObject(myMoudleInfoString,MyModuleInfo.class);
                if(myModuleInfo!=null)
                {
                    nicker_name.setText(myModuleInfo.getUname());
                    Integer score=myModuleInfo.getIntegral();
                    if(score!=null)
                    {
                        tv_score.setVisibility(View.GONE);
                        tv_score.setText("积分 "+score);
                    }else {
                        tv_score.setVisibility(View.GONE);
                    }
                    Glide.with(context).load(myModuleInfo.getPurl())
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.mipmap.own_pic_logout)
                            .into((ImageView) head_icon);
                }
            }catch (Exception e)
            {

            }
        }
    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //banner
            if (flag.equals(MY_MODULE_STATE_FLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    MyModuleStateBean myModuleStateBean=JsonTools.jsonStringToObject(jsonMessage,MyModuleStateBean.class);
                    if(myModuleStateBean!=null)
                    {
                        int baoming=myModuleStateBean.getSignup();//報名
                        int fabu=myModuleStateBean.getPublish();//發佈
                        int shenqing=myModuleStateBean.getApply();//受理中心
                        int yuyue=myModuleStateBean.getAppointment();//服务预约
                        int fankui=myModuleStateBean.getFeedback();//曝光台
                        int message=myModuleStateBean.getMessage();//消息
                        if(baoming>0)
                        {
                            baoming_point.setVisibility(View.VISIBLE);
                        }else
                        {
                            baoming_point.setVisibility(View.GONE);
                        }

                        if(fabu>0)
                        {
                            fabu_point.setVisibility(View.VISIBLE);
                        }else
                        {
                            fabu_point.setVisibility(View.GONE);
                        }

                        if(shenqing>0)
                        {
                            shenqing_point.setVisibility(View.VISIBLE);
                        }else
                        {
                            shenqing_point.setVisibility(View.GONE);
                        }

                        if(yuyue>0)
                        {
                            yuyue_point.setVisibility(View.VISIBLE);
                        }else
                        {
                            yuyue_point.setVisibility(View.GONE);
                        }

                        if(fankui>0)
                        {
                            fankui_point.setVisibility(View.VISIBLE);
                        }else
                        {
                            fankui_point.setVisibility(View.GONE);
                        }

                        if(message>0)
                        {
                            iv_message.setImageDrawable(context.getResources().getDrawable(R.mipmap.message2x));
                        }else {
                            iv_message.setImageDrawable(context.getResources().getDrawable(R.mipmap.messageno));
                        }
                    }
                }

            }
          else if (flag.equals(MY_MODULE_INFO_FLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String messageJson=JsonTools.objectToJsonString(object);
                    myMoudleInfoString=messageJson;
                    final MyModuleInfo myModuleInfo=JsonTools.jsonStringToObject(myMoudleInfoString,MyModuleInfo.class);
                    if(myModuleInfo!=null)
                    {
                        nicker_name.setText(myModuleInfo.getUname());
                        Integer score=myModuleInfo.getIntegral();
                        if(score!=null)
                        {
                            tv_score.setVisibility(View.GONE);
                            tv_score.setText("积分 "+score);
                        }else {
                            tv_score.setVisibility(View.GONE);
                        }

                        final String uid= Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);

//                        Bitmap bitmap = null;
//                        try {
//                            bitmap = Tools.getBitmap(myModuleInfo.getPurl());
//                        } catch (Exception e) {
//                            // TODO: handle exception
//                        }
//                        if (bitmap != null) {
//                            SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
//                            if (softBitmap != null && softBitmap.get() != null)
//                                Tools.WriteImaToSdcard(getActivity(), softBitmap.get(), Constant.wsc_photo, "userid" + userid + ".jpg");
//                            bitmap = null;
//                        }

                        AbPermissionUtils.requestPermissionsResult(this, 1
                                , new String[]{
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                  }
                                , new AbPermissionUtils.OnPermissionListener() {
                                    @Override
                                    public void onPermissionGranted() {
                                        File file = new File(new File(Environment.getExternalStorageDirectory(), Constant.wsc_photo), "userid" + uid + ".jpg");
                                        if (file.exists()) {
                                            initBitmap = BitmapFactory.decodeFile(file.getPath());
                                            if (initBitmap != null) {
                                                SoftReference<Bitmap> softbitmap = new SoftReference<Bitmap>(initBitmap);
                                                if (softbitmap != null && softbitmap.get() != null) {
                                                    Drawable drawable = new BitmapDrawable(softbitmap.get());
                                                    head_icon.setImageDrawable(drawable);
                                                }
                                            }
//                                            else
//                                            {
//                                                Glide.with(context).load(myModuleInfo.getPurl())
//                                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                                                        .placeholder(R.mipmap.own_pic_logout)
//                                                        .into((ImageView) head_icon);
//                                            }

                                        } else {
                                            Glide.with(context).load(myModuleInfo.getPurl())
                                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                    .placeholder(R.mipmap.own_pic_logout)
                                                    .into((ImageView) head_icon);
                                        }
                                    }

                                    @Override
                                    public void onPermissionDenied() {

                                    }
                                });
                    }
                    Tools.setSharedPreferencesStrings(Constant.SharePreferenceMyModuleInfo,messageJson,context);
                }
            }

        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {

    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ishide = hidden;
        if(hidden)
        {
        }else
        {
            getData();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ishide) {

        } else {
            getData();
        }

        MobclickAgent.onPageStart(MineFragment.class.getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(MineFragment.class.getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (initBitmap != null && !initBitmap.isRecycled()) {
            initBitmap.recycle();
            initBitmap = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.head_icon:
                Intent person_info_intent=new Intent(context,PersonInfoActivity.class);
                startActivity(person_info_intent);
                break;
            case R.id.iv_edit:
                Intent edit_intent=new Intent(context,PersonInfoActivity.class);
                startActivity(edit_intent);
                break;
            case R.id.setting:
                Intent setting_intent=new Intent(context,SettingActivity.class);
                startActivity(setting_intent);
                break;
            case R.id.message:
                Intent message_intent=new Intent(context,MessageActivity.class);
                startActivity(message_intent);
                break;
            //我的报名
            case R.id.bottom_content_one:
                Intent baoming_intent=new Intent(context,MyBaoMingActivity.class);
                startActivity(baoming_intent);
                break;
            //我的发布
            case R.id.bottom_content_two:
                Intent shenqing_intent=new Intent(context, MyFaBuActivity.class);
                startActivity(shenqing_intent);
                break;
            //我的申请
            case R.id.bottom_content_three:
                Intent wish_intent=new Intent(context, ShouLiCenterActivity.class);
                wish_intent.putExtra("name","受理中心");
                startActivity(wish_intent);
                break;
            //我的预约
            case R.id.bottom_content_four:
                Intent yuYue_intent=new Intent(context, MyYuYueActivity.class);
                yuYue_intent.putExtra("name","服务预约");
                startActivity(yuYue_intent);
                break;
            //曝光台
            case R.id.bottom_content_five:
                fankui_point.setVisibility(View.GONE);
                Intent fankui_intent=new Intent(context, MyBackActivity.class);
                startActivity(fankui_intent);
                break;
//            case R.id.bottom_content_six:
//                Intent pingfen_intent=new Intent(getActivity(), PingfenActivity.class);
//                startActivity(pingfen_intent);
//                break;
//            case R.id.bottom_content_seven:
//                Intent shoucang_intent=new Intent(getActivity(), ShoucangActivity.class);
//                startActivity(shoucang_intent);
//                break;
        }
    }
}
